<template>
  <el-card class="card">
    <div ref="container" class="container" style="font-size: 14px">
      <!--    <div><img src="http://192.168.31.224:8000/hello" alt="111"></div>-->

      <el-row style="margin: 10px;" :gutter="10">
        <el-col :span="5">
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="8">违禁品名称:</el-col>
            <el-col :span="16">
              <el-input v-model="form.condition.name" placeholder="请输入违禁品名称" size="mini" style="display:inline" />
            </el-col>
          </el-row>

        </el-col>
        <el-col :span="10">
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="6">时间范围:</el-col>
            <el-col :span="18">
              <el-date-picker
                v-model="timeRange"
                type="datetimerange"
                range-separator="至"
                size="mini"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                value-format="timestamp"
                @change="convertTimeFormat"
              />
            </el-col>
          </el-row>
        </el-col>
        <!--        <el-col :span="5">-->
        <!--          <el-row type="flex" justify="center" align="middle">-->
        <!--            <el-col :span="6">结束时间:</el-col>-->
        <!--            <el-col :span="18">-->
        <!--              <el-date-picker-->
        <!--                v-model="form.condition.endTime"-->
        <!--                type="datetime"-->
        <!--                size="mini"-->
        <!--                placeholder="选择日期时间"-->
        <!--                style="width: 100%"-->
        <!--              />-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </el-col>-->
        <el-col :span="5">
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="6">作业地点:</el-col>
            <el-col :span="18">
              <el-input v-model="form.condition.place" placeholder="请输入作业地点" size="mini" style="display:inline" />
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="4" :offset="0.5">
          <el-row type="flex" justify="center" align="middle">
            <el-button type="primary" size="small" @click="getDataByPageAndCondition">查询</el-button>
            <el-button size="small" type="primary" @click="exportSelected">导出选中
            </el-button>
            <el-button size="small" type="danger" @click="open_message_popUp">删除选中
            </el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-table
        ref="multipleTable"
        :data="tables"
        border
        style="width: 100%"
        stripe
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="违禁品名称" />
        <el-table-column prop="time" label="时间" />
        <el-table-column prop="place" label="作业地点" />
        <el-table-column prop="view" label="输入视角">
          <template v-slot="scope">
            <span v-if="scope.row.view===0">上视角</span>
            <span v-else>下视角</span>
          </template>
        </el-table-column>
        <el-table-column prop="originalImage" label="原始图像">

          <template v-slot="scope">
            <!-- 点击图片执行打开模态窗口操作 -->
            <img
              :alt="'加载失败'"
              :src="baseURL + encodeURI(scope.row.originalImagePath)"
              :height="imageHeight"
              @click="openImage(baseURL + encodeURI(scope.row.originalImagePath), '原始图像', { name: scope.row.name, time: scope.row.time })"
            >
          </template>
        </el-table-column>
        <el-table-column prop="detectedImagePath" label="检测图像">
          <template v-slot="scope">
            <!-- 与上同理 -->
            <img
              :alt="'加载失败'"
              :src="baseURL + encodeURI(scope.row.detectedImagePath)"
              :height="imageHeight"
              @click="openImage(baseURL + encodeURI(scope.row.detectedImagePath), '检测图像', { name: scope.row.name, time: scope.row.time })"
            >
          </template>

        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleDerive(encodeURI(scope.row.originalImagePath),encodeURI(scope.row.detectedImagePath))"
            >导出
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 图片查看对话框
      <el-dialog :visible.sync="showDialog" width="80%" @close="closeDialog">
        <img :src="currentImagePath" alt="图片加载失败" style="width: 100%">
      </el-dialog> -->

      <!-- 图片查看对话框 -->
      <el-dialog :visible.sync="showDialog" width="80%" @close="closeDialog">
        <!-- 标题栏，显示违禁品名称、时间和类型 -->
        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; background-color: #f5f5f5; font-weight: bold;">
          <div>
            <span>违禁品名称: {{ selectedItem.name }}</span> |
            <span>时间: {{ selectedItem.time }}</span> |
            <span>图像类型: {{ imageType }}</span>
          </div>
          <div>
            <span>{{ imageType }}</span>
          </div>
        </div>
        <!-- 包裹图片的容器 -->
        <div style="position: relative; width: 100%; height: 100%;">
          <!-- 显示当前图片 -->
          <img :src="currentImagePath" alt="图片加载失败" style="width: 100%; display: block;">
          <!-- 左边区域点击切换到上一张 -->
          <div
            style="position: absolute; top: 50%; left: 10px; transform: translateY(-50%); z-index: 10; cursor: pointer; background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 50%;"
            @click="previousImage"
          >
            <i class="el-icon-arrow-left" style="color: white; font-size: 24px;" />
          </div>

          <!-- 右边区域点击切换到下一张 -->
          <div
            style="position: absolute; top: 50%; right: 10px; transform: translateY(-50%); z-index: 10; cursor: pointer; background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 50%;"
            @click="nextImage"
          >
            <i class="el-icon-arrow-right" style="color: white; font-size: 24px;" />
          </div>
        </div>
      </el-dialog>

      <div class="block" style=" width: 50%;margin: 0 auto;">
        <!--.sync 是 Vue.js 2.x 版本中的一种属性绑定语法，用于实现双向数据绑定。
        它通常用在父子组件之间，允许子组件修改一个 prop 的值，然后将这个修改传递回父组件。
        在 Vue.js 3.x 中，.sync 语法已经被废弃，取而代之的是 v-model 的新语法。-->
        <el-pagination
          :current-page="form.page_info.page"
          :page-size="form.page_info.per_page"
          :page-sizes="[10, 20, 50, 100, total]"
          layout="total, sizes, prev, pager, next, jumper, ->, slot"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </el-card>
</template>
<script>

import { deleteSelected, derive, getDataByPageAndCondition } from '@/api/dataQueryAndStatistics'
import { str } from 'mockjs/src/mock/random/basic'
import path from 'path'

export default {
  data() {
    return {
      screenWidth: (6 / 7) * window.innerWidth,
      screenHeight: (6 / 7) * window.innerHeight,
      showDialog: false,
      currentImagePath: '',
      form: {
        condition: {
          name: '',
          startTime: '',
          endTime: '',
          place: ''
        },
        page_info: {
          // 每页数据数量
          per_page: 10,
          // 当前页号
          page: 1
        }
      },
      chart1: '',
      chart2: '',
      tables: [],
      total: 1,
      baseURL: '/dataQuery/getImageByPath?path=',
      imageWidth: this.screenWidth / 6,
      imageHeight: this.screenHeight / 7.5,
      // 存储已勾选的对象
      multipleSelection: [],
      // 存储用户选择的时间范围
      timeRange: [],
      images: [], // 存储所有图片的路径
      currentIndex: 0, // 当前显示图片的索引
      imageType: '', // '原始图像' 或 '检测图像'
      selectedItem: {
        name: '',
        time: ''
      },
      imageType_list: [],
      selectedItem_list: []
    }
  },
  computed: {
    textStyle() {
      return 'fontSize:' + (this.screenWidth / 100 + 2 + 'px')
    },
    // 从multipleSelection中提取item_id属性生成的数组
    selectIdList() {
      const idList = []

      for (let i = 0; i < this.multipleSelection.length; i++) {
        idList.push(this.multipleSelection[i].id)
      }
      return idList
    }
  },
  watch: {},
  created() {

  },
  mounted() {
    this.listenResizeEvent()
    // 加载页面时自动显示第一页数据
    this.getDataByPageAndCondition()
  },
  methods: {
    str,
    handleResize() {
      this.screenWidth = (6 / 7) * window.innerWidth
      this.screenHeight = (6 / 7) * window.innerHeight
      this.imageWidth = this.screenWidth / 6
      this.imageHeight = this.screenHeight / 7.5
    },
    listenResizeEvent() {
      window.addEventListener('resize', this.handleResize)
    },
    removeResizeEvent() {
      window.removeEventListener('resize', this.handleResize)
    },
    // 添加模态窗口进行放大
    // openImage(imageUrl) {
    //   this.currentImagePath = imageUrl
    //   this.showDialog = true
    // },
    // 关闭模态窗口
    closeDialog() {
      this.showDialog = false
    },
    getDataByPageAndCondition() {
      getDataByPageAndCondition(this.form).then(response => {
        this.tables = response.data.list
        for (let i = 0; i < this.tables.length; i++) {
          this.tables[i].time = new Date(this.tables[i].time).toLocaleString()
        }

        this.handleResize()
        this.total = response.data.total
        // this.total = JSON.parse(response.total)

        // 初始化放大窗口参数
        this.imageType_list = []
        this.selectedItem_list = []
        this.images = []
        for (let i = 0; i < this.tables.length; i++) {
          console.log('changdu', this.tables.length)
          this.images.push(this.baseURL + encodeURI(this.tables[i].originalImagePath)) // 使用push方法将新的URL添加到images数组中
          this.images.push(this.baseURL + encodeURI(this.tables[i].detectedImagePath)) // 使用push方法将新的URL添加到images数组中
          this.selectedItem = {
            name: this.tables[i].name,
            time: this.tables[i].time
          }
          console.log('this.selectedItem', this.selectedItem)
          this.selectedItem_list.push(this.selectedItem)
          this.selectedItem_list.push(this.selectedItem)
          this.imageType_list.push('原始图像')
          this.imageType_list.push('检测图像')
        }
        console.log('changdu', this.tables.length)
        console.log('images', this.images)
        console.log('imageType_list', this.imageType_list)
        console.log('selectedItem_list', this.selectedItem_list)
      }).catch(e => {
        console.log(e)
      })
    },
    // 当page-sizes变化时调用该函数
    handleSizeChange(val) {
      // form.page_info.per_page
      this.form.page_info.per_page = val
      this.getDataByPageAndCondition()
      console.log(`每页 ${val} 条`)
    },
    // currentPage 改变时会触发
    async handleCurrentChange(val) {
      this.form.page_info.page = val
      // 调用查询
      await this.getDataByPageAndCondition(this.form)
      // console.log('after', this.selectedItem_list)
      console.log(`当前页: ${val}`)
    },
    // 处理选中删除
    deleteSelected() {
      console.log(this.selectIdList)
      //   向后端传输id
      deleteSelected(this.selectIdList).then((response) => {
        // console.log(response)
        if (response.status !== 200) {
          this.$message({
            type: 'error',
            message: '删除失败,' + response.message
          })
        } else {
          // 通知删除成功
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }

        //   重新更新页面
        getDataByPageAndCondition(this.form).then(response => {
          this.tables = response.data.list
          for (let i = 0; i < this.tables.length; i++) {
            this.tables[i].time = new Date(this.tables[i].time).toLocaleString()
          }
          this.handleResize()
          this.total = response.data.total
        }).catch(e => {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
          console.log(e)
        })
      }).catch(e => {
        this.$message({
          type: 'error',
          message: '删除失败'
        })
        console.log(e)
      })
    },

    // 实现消息弹窗：带确认和取消按钮
    open_message_popUp() {
      this.$confirm('是否删除选中条目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点了确定后再执行删除操作
        this.deleteSelected()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 处理选中导出
    exportSelected() {
      for (let i = 0; i < this.multipleSelection.length; i++) {
        const image = this.multipleSelection[i]
        this.handleDerive(image['originalImagePath'], image['detectedImagePath'])
      }
    },
    // 处理单条目数据导出
    handleDerive(original_img_path, detected_img_path) {
      // 使用正则表达式和replace()函数，替换字符串中的所有匹配项
      const pattern = /\\/g
      original_img_path = original_img_path.replace(pattern, '/')
      detected_img_path = detected_img_path.replace(pattern, '/')

      derive(original_img_path).then(response => {
        // 调用导出
        this.exportImage(response.data, original_img_path)
      }).catch(error => {
        // 处理请求错误
        console.error('Error downloading file:', error)
      })
      derive(detected_img_path).then(response => {
        // 调用导出
        this.exportImage(response.data, detected_img_path)
      }).catch(error => {
        // 处理请求错误
        console.error('Error downloading file:', error)
      })
    },
    // 通过创建链接导出图片
    exportImage(response_blob, url) {
      // 创建一个链接
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(response_blob)
      // 通过path.basename()函数解析文件路径设置文件名字
      link.download = path.basename(url)
      // 将链接插入到文档中
      document.body.appendChild(link)
      // 模拟点击链接进行下载
      link.click()
      // 下载完成后移除链接
      document.body.removeChild(link)
    },
    // 处理选中后的变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    convertTimeFormat() {
      const temp = []
      for (let i = 0; i < this.timeRange.length; i++) {
        temp.push(this.timeRange[i])
      }
      // 更新参数
      this.form.condition.startTime = temp[0]
      this.form.condition.endTime = temp[1]
    },
    // 添加方法以打开图片并设置当前图片索引
    openImage(imageUrl, imageType, item) {
      this.currentIndex = this.images.indexOf(imageUrl)
      if (this.currentIndex === -1) {
        this.currentIndex = 0
      }
      this.currentImagePath = imageUrl
      this.imageType = imageType
      this.selectedItem = item
      this.showDialog = true
      // console.log(this.currentIndex)
      // console.log(this.images)
      // console.log(this.currentImagePath)
    },
    // 切换到上一张图片
    previousImage() {
      if (this.currentIndex > 0) {
        this.currentIndex -= 1
      } else {
        this.currentIndex = this.images.length - 1 // 如果是第一张，则切换到最后一张
      }
      this.currentImagePath = this.images[this.currentIndex]
      this.imageType = this.imageType_list[this.currentIndex]
      this.selectedItem = this.selectedItem_list[this.currentIndex]
      console.log(this.currentIndex)
      console.log(this.selectedItem.name)
      console.log(this.selectedItem.time)
    },
    // 切换到下一张图片
    nextImage() {
      if (this.currentIndex < this.images.length - 1) {
        this.currentIndex += 1
      } else {
        this.currentIndex = 0 // 如果是最后一张，则切换到第一张
      }
      this.currentImagePath = this.images[this.currentIndex]
      this.imageType = this.imageType_list[this.currentIndex]
      this.selectedItem = this.selectedItem_list[this.currentIndex]
      console.log(this.currentIndex)
      console.log(this.selectedItem.name)
      console.log(this.selectedItem.time)
    }
  }
}

</script>

<style>
.card {
  margin: 20px;
  .container {
    font-size: 12px;
  }
}
/* 为半透明箭头添加一些样式 */
.el-dialog__body {
  padding: 0;
}

.el-icon-arrow-left, .el-icon-arrow-right {
  transition: transform 0.3s ease;
}

.el-icon-arrow-left:hover, .el-icon-arrow-right:hover {
  transform: scale(1.2);
}
</style>

